<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 15:13
 */
namespace App\Services;

use App\Repositories\DistributGroupRepository;
use App\Repositories\DistributProfitRepository;
use App\Repositories\DistributRepository;
use App\Repositories\UserLevelPassageBankRepository;
use App\Repositories\UserLevelPassageRepository;
use App\Repositories\UserLevelProfitRepository;
use App\Repositories\UserProfitRepository;
use App\Repositories\UserRepository;

class DistributService extends CommonService
{
    protected $userProfitRepository;
    protected $userRepository;
    protected $userLevelProfitRepository;
    protected $userLevelPassageRepository;
    protected $userLevelPassageBankRepository;
    protected $distributRepository;
    protected $distributGroupRepository;
    protected $distributProfitRepository;
    protected $invitedService;
    protected $messageService;

    public function __construct(UserProfitRepository $userProfitRepository,
                                UserRepository $userRepository,
                                UserLevelProfitRepository $userLevelProfitRepository,
                                UserLevelPassageRepository $userLevelPassageRepository,
                                UserLevelPassageBankRepository $userLevelPassageBankRepository,
                                DistributRepository $distributRepository,
                                DistributGroupRepository $distributGroupRepository,
                                DistributProfitRepository $distributProfitRepository,
                                InvitedService $invitedService,
                                MessageService $messageService)
    {
        $this->userProfitRepository = $userProfitRepository;
        $this->userRepository = $userRepository;
        $this->userLevelProfitRepository = $userLevelProfitRepository;
        $this->userLevelPassageRepository = $userLevelPassageRepository;
        $this->userLevelPassageBankRepository = $userLevelPassageBankRepository;
        $this->distributRepository = $distributRepository;
        $this->distributGroupRepository = $distributGroupRepository;
        $this->distributProfitRepository = $distributProfitRepository;
        $this->invitedService = $invitedService;
        $this->messageService = $messageService;
    }

    /**
     * 获取分销商团队
     * @param $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupMember($userId)
    {
        $distribut = $this->distributRepository->byUserId($userId);
        if (empty($distribut)) {
            return $this->responseJson(12001);//未开通服务商入口权限
        }
        $data = $this->distributGroupRepository->getGroupMember($distribut->id);
        return $this->responseJson(0, $data);
    }

    public function distributProfit($userId, $dateFormat, $dateFormatType,
                                    $groupMemberId, $startDate, $endDate)
    {
        //验证最长的天数差为31天
        $diffDays = diffDate($startDate, $endDate);
        if ($diffDays > 31) {
            return $this->responseJson(12002);//自定义最长天数差为31天
        }
        $distribut = $this->distributRepository->byUserId($userId);
        if (empty($distribut)) {
            return $this->responseJson(12001);//未开通服务商入口权限
        }
        $dateTime =[];
        if ($dateFormatType == 'has_one') {
            $dateTime = $this->dateTimeFormat($dateFormat);
        }
        if ($dateFormatType == 'has_many') {
            $dateTime = [
                'start_time' => strtotime($startDate),
                'end_time' => strtotime($endDate),
            ];
        }
        $distributProfit = '0.00';
        $distributProfitAll = '0.00';
        $groupUserIds = [0];
        if ($groupMemberId == 0) {
            $groupMemberGetIds = $this->distributGroupRepository->getGroupMemberIds($distribut->id);
            $groupMemberGetIds = $groupMemberGetIds->toArray();
            if (!empty($groupMemberGetIds)) {
                $groupUserIds = array_column($groupMemberGetIds, 'group_user_id');
            }
            $distributProfit = $this->distributProfitRepository->profitByCreateTime($distribut->id, $dateTime['start_time'], $dateTime['end_time']);
            $distributProfitAll = $this->distributProfitRepository->profitAll($distribut->id);
        }
        if ($groupMemberId > 0) {
            $group = $this->distributGroupRepository->byId($groupMemberId);
            if (!empty($group)) {
                $groupUserIds = [$group->group_user_id];
            }
            $distributProfit = $this->distributProfitRepository->profitByCreateTimeFromGroupId($distribut->id, $groupMemberId, $dateTime['start_time'], $dateTime['end_time']);
            $distributProfitAll = $this->distributProfitRepository->profitAllFromGroupId($distribut->id, $groupMemberId);
        }
        $groupMemberProfit = $this->userProfitRepository->profitByCreateTime($groupUserIds, $dateTime['start_time'], $dateTime['end_time']);
        $groupMemberProfitAll = $this->userProfitRepository->profitGroupAll($groupUserIds);
        $data = [
            'group_member_profit' => [
                'profit' => $groupMemberProfit,
                'profit_all' => $groupMemberProfitAll,
            ],
            'group_member_resgister' => $this->registerCount($groupUserIds, $dateTime['start_time'], $dateTime['end_time']),
            'distribut_profit' => [
                'profit' => $distributProfit,
                'profit_all' => $distributProfitAll,
            ],
        ];
        return $this->responseJson(0, $data);
    }

    protected function registerCount($groupUserIds, $startTime, $endTime)
    {
        $invitedCount = [];
        $invitedAllCount = [];
        foreach ($groupUserIds as $key=>$value) {
            if ($value > 0) {
                $invitedCount[$key] = $this->invitedService->invitedCount($value, true, $startTime, $endTime);
                $invitedAllCount[$key] = $this->invitedService->invitedCount($value);
            }
        }
        $directInvited = array_sum(array_column($invitedCount, 'direct_invited_number'));
        $indirectInvited = array_sum(array_column($invitedCount, 'indirect_invited_number'));
        $directInvitedAll = array_sum(array_column($invitedAllCount, 'direct_invited_number'));
        $indirectInvitedAll = array_sum(array_column($invitedAllCount, 'indirect_invited_number'));
        return [
            'new_resgister_direct' => (string)$directInvited,
            'new_resgister_indirect' => (string)$indirectInvited,
            'resgister_count' => (string)($directInvitedAll + $indirectInvitedAll),
        ];
    }

    public function createGroup($user, $groupName, $groupMobile, $profitPercent)
    {
        $distribut = $this->distributRepository->byUserId($user['user_id']);
        if (empty($distribut)) {
            return $this->responseJson(12001);//未开通服务商入口权限
        }
        if ($profitPercent < 1 || $profitPercent > 100) {
            return $this->responseJson(12003);//团队分润比例1-100%
        }
        if ($user['mobile'] == $groupMobile) {
            return $this->responseJson(12006);//不支持添加本人作为团队
        }
        $isUser = $this->userRepository->byMobile($groupMobile);
        if (empty($isUser)) {
            return $this->responseJson(12007);//该手机号码在平台未注册
        }
        $memberCount = $distribut->group_member_number;
        $alreadyPassMemberCount = $this->distributGroupRepository->groupMemberCountLimit($distribut->id);
        if ($alreadyPassMemberCount >= $memberCount) {
            return $this->responseJson(12005);//超出团队成员数量
        }
        $isExistGroupMember = $this->distributGroupRepository->isBindGroupMember($groupMobile);
        if (!empty($isExistGroupMember)) {
            return $this->responseJson(12008);//该团队已被其他服务商绑定
        }
        $isExistGroupMember = $this->distributGroupRepository->isExistGroupMember($distribut->id, $groupMobile);
        if (!empty($isExistGroupMember)) {
            return $this->responseJson(12004);//该团队已存在，请勿重复添加
        }
        $data = [
            'distribut_id' => $distribut->id,
            'distribut_user_id' => $user['user_id'],
            'group_name' => $groupName,
            'group_mobile' => $groupMobile,
            'profit_percent' => round($profitPercent / 100, 2),
        ];
        $this->distributGroupRepository->create($data);
        return $this->responseJson(0);
    }

    public function groupCount($userId)
    {
        $distribut = $this->distributRepository->byUserId($userId);
        if (empty($distribut)) {
            return $this->responseJson(12001);//未开通服务商入口权限
        }
        $memberCount = $distribut->group_member_number;
        $alreadyPassMemberCount = $this->distributGroupRepository->groupMemberCount($distribut->id);
        $waitPassMemberCount = $this->distributGroupRepository->groupMemberCountWaitPass($distribut->id);
        $data = [
            'count' => (string)$memberCount,//总数量
            'has_count' => $alreadyPassMemberCount,//审核通过
            'wait_count' => $waitPassMemberCount,//待审核与审核中
        ];
        return $this->responseJson(0, $data);
    }

    protected function dateTimeFormat($dateFormat)
    {
        switch ($dateFormat) {
            case 'today':
                $startTime = mktime(0,0,0,date('m'),date('d'),date('y'));
                $endTime = time();
                break;
            case 'yesterday':
                $startTime = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                $endTime = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
                break;
            case 'week':
                $startTime = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));
                $endTime = time();
                break;
            case 'month':
                $startTime = mktime(0,0,0,date('m'),1,date('y'));
                $endTime = time();
                break;
            default:
                $startTime = mktime(0,0,0,date('m'),date('d'),date('y'));
                $endTime = time();
                break;
        }
        return [
            'start_time' => $startTime,
            'end_time' => $endTime,
        ];
    }
}